import { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { Table, Modal, Card, Icon } from 'antd';

import DescriptionList from 'components/DescriptionList';
import { getStatusDesc, getRefundStatusDesc } from './utils';

const { Description } = DescriptionList;

class DetailModal extends Component {
  componentDidMount() {
    const { orderId } = this.props;
    this.handleFetchDetail(orderId);
  }

  componentWillReceiveProps(nextProps) {
    const { orderId } = nextProps;
    const { orderId: oldOrderId } = this.props;

    if (orderId !== oldOrderId) {
      this.handleFetchDetail(orderId);
    }
  }

  handleFetchDetail = orderId => {
    const { onCancel } = this.props;

    if (!orderId) {
      return;
    }

    this.props
      .dispatch({
        type: 'orders/fetch',
        payload: orderId,
      })
      .then(({ code }) => {
        // 数据获取失败则关闭弹窗，避免展示的旧数据
        if (code) {
          onCancel();
        }
      });
  };

  render() {
    const { orderDetail, loading, onCancel } = this.props;
    const {
      tradeNo,
      product,
      totalAmount,
      status,
      user,
      createdAt,
      paidAt,
      items,
      refunds,
    } = orderDetail;
    const orderStatus = getStatusDesc(status);
    const levelDataSource = items || [];
    let oldRefunds = refunds || [];
    let refundDataSource = [];

    // 每一次申请退款就生成一条记录，确认或取消（后台）是直接更新此记录的状态
    // 这里处理下数据，把每次改动都作为一条记录展示（直观）
    oldRefunds.forEach(item => {
      const { status, updatedAt } = item;

      if (status === 0) {
        refundDataSource.push(item);
      } else {
        refundDataSource.push({
          ...item,
          createdAt: updatedAt,
        });
        refundDataSource.push({
          ...item,
          status: 0,
        });
      }
    });

    // 购买系列
    const levelColumns = [
      {
        title: '系列ID',
        dataIndex: 'courseId',
        key: 'courseId',
      },
      {
        title: '系列',
        dataIndex: 'level',
        key: 'level',
        render: level => {
          return <span>Level {level}</span>;
        },
      },
      {
        title: '原价(¥)',
        dataIndex: 'price',
        key: 'price',
      },
      {
        title: '优惠(¥)',
        dataIndex: 'discountPrice',
        key: 'discountPrice',
      },
      {
        title: '实际金额(¥)',
        key: 'real',
        render: (text, record) => (
          <span>{(Number(record.price) - Number(record.discountPrice)).toFixed(2)}</span>
        ),
      },
    ];

    // 退款历史记录
    const refundColumns = [
      {
        title: '状态',
        dataIndex: 'status',
        render: status => {
          return <span>{getRefundStatusDesc(status)}</span>;
        },
      },
      {
        title: '备注',
        dataIndex: 'remark',
        key: 'remark',
      },
      {
        title: '退款金额(¥)',
        dataIndex: 'refundAmount',
        key: 'refundAmount',
      },
      {
        title: '操作时间',
        dataIndex: 'createdAt',
        key: 'createdAt',
      },
    ];

    return (
      <Modal
        title={
          <>
            <Icon type="shopping-cart" />
            &nbsp;&nbsp;订单详情
          </>
        }
        onCancel={onCancel}
        width={'80%'}
        style={{ maxWidth: 1024, minWidth: 780 }}
        visible={true}
        maskClosable={true}
        footer={null}>
        <Card bordered={false} loading={loading}>
          <DescriptionList style={{ marginBottom: 24 }}>
            <Description term="订单号">{tradeNo}</Description>
            <Description term="订单金额(¥)">{totalAmount}</Description>
            <Description term="订单状态">
              {orderStatus}
              &nbsp;
              {orderStatus === '支付成功' && (
                <Icon style={{ color: '#52c41a' }} type="check-circle" />
              )}
            </Description>
          </DescriptionList>
          <DescriptionList style={{ marginBottom: 24 }}>
            <Description term="支付方式">微信支付</Description>
            <Description term="下单时间">{createdAt}</Description>
            <Description term="支付时间">{paidAt}</Description>
          </DescriptionList>
          <DescriptionList style={{ marginBottom: 24 }}>
            <Description term="购买系列">见下表</Description>
            <Description term="商品名称">{product}</Description>
            <Description term="客户昵称">{user ? user.nickname : ''}</Description>
          </DescriptionList>
          <Table
            bordered
            columns={levelColumns}
            dataSource={levelDataSource}
            rowKey={record => record.id}
            pagination={false}
          />
          {refundDataSource.length > 0 && (
            <>
              <h3 style={{ marginTop: 30 }}>退款历史记录</h3>
              <Table
                bordered
                columns={refundColumns}
                dataSource={refundDataSource}
                rowKey={record => record.id}
                pagination={false}
              />
            </>
          )}
        </Card>
      </Modal>
    );
  }
}

if (process.env.UMI_ENV !== 'prod') {
  DetailModal.propTypes = {
    onCancel: PropTypes.func.isRequired,
    dispatch: PropTypes.func.isRequired,
    orderDetail: PropTypes.object.isRequired,
    loading: PropTypes.bool.isRequired,
    orderId: PropTypes.number.isRequired,
  };
}

DetailModal.defaultProps = {
  dispatch: () => {},
  onCancel: () => {},
  orderDetail: {},
  loading: false,
  orderId: 0,
};

function mapStateToProps({ orders, loading }, { orderId }) {
  const { orderDetail } = orders;

  return {
    orderDetail,
    orderId,
    loading: loading.effects['orders/fetch'],
  };
}

export default connect(mapStateToProps)(DetailModal);
